﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using iLib.Web.UI;

namespace Cms.Web.UI.Admin
{
    public partial class EditUser :  AdminPage, IEditUserView
    {
        private EditUserPresenter _presenter;

        #region IEditUserView Members

        public int EditedUserID
        {
            get
            {
                if (hidEditedUserID.Value == "")
                    hidEditedUserID.Value = QueryString.GetInt32ID("id").ToString();
                return int.Parse(hidEditedUserID.Value);
            }
        }

        public void SetEditedUserID(int id)
        {
            hidEditedUserID.Value = id.ToString();
        }

        public string CurrentTab
        {
            get { return tabStrip.CurrentValue; }
        }

        public string Username
        {
            get { return txtUsername.Text; }
            set { txtUsername.Text = value; }
        }

        public string Password
        {
            get { return txtPassword.Text; }
            set { txtPassword.Text = value; }
        }

        public string Email
        {
            get { return txtEmail.Text; }
            set { txtEmail.Text = value; }
        }

        public string Firstname
        {
            get { return txtFirstname.Text; }
            set { txtFirstname.Text = value; }
        }

        public string Lastname
        {
            get { return txtLastname.Text; }
            set { txtLastname.Text = value; }
        }

        public string Phone
        {
            get { return txtPhone.Text; }
            set { txtPhone.Text = value; }
        }

        public string ContextTranslationFile
        {
            get { return "Admin/Translations/EditUser.xml"; }
        }

        public void SetHeading(string text)
        {
            HeadingText = EditedUserID > 0
                              ? GetText(this, "EditUserHeading") + " &mdash; " + text
                              : GetText(this, "NewUserHeading");
        }

        public void SetMemberships(IList<Membership> memberships)
        {
            rpMemberships.DataSource = memberships;
            rpMemberships.DataBind();
            trNoHits.Visible = rpMemberships.Items.Count == 0;
        }

        #endregion
        
        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new EditUserPresenter(this);
            if (!Page.IsPostBack)
            {
                if (EditedUserID > 0)
                    tabStrip.SelectedValue = Request.QueryString["tab"];
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
                txtUsername.Focus();
            }
            lbDeleteMembership.OnClientClick = "return cms.Dialogs.ConfirmLinkButton(this, " +
                             "function (status) { " +
                             "if (status == 'ok') " +
                             "cms.Lists.ShowPaneOverlay('membershipPaneOverlay');" +
                             "else " +
                             "cms.Lists.HidePaneOverlays(); " +
                             "}, " +
                             "'" + GetText(this, "DeleteHeader") + "', " +
                             "'" + GetText(this, "DeleteMessage") + "', " +
                             "'" + GetText(this, "DeleteOK") + "', " +
                             "'" + GetText(this, "DeleteCancel") + "', " +
                             "true, " +
                             "cms.Lists.CurrentName);";
        }

        private string GetSaveInfoMessageKey()
        {
            return EditedUserID > 0 ? "OptionalSaveInfoMessage" : "ForceSaveInfoMessage";
        }

        private string GetClientClickScript(AdminTabItem ti)
        {
            return "cms.Edit.ShowTabOverlays(); " +
                   "if (isDirty()) {" +
                   "return cms.Dialogs.Confirm(" +
                   "function (status) { " +
                   "document.getElementById('ctl00_tabs_hidSave').value = status;" +
                   "var userID = document.getElementById('ctl00_tabs_hidEditedUserID').value;" +
                   "if ((userID == '' || userID == '-1') && status != 'ok') " +
                   "cms.Edit.HideTabOverlays(); " +
                   "else " +
                   "__doPostBack('" + ti.UniqueID + "$" + ti.ID + "','');" +
                   "}, " +
                   "'" + GetText(this, "SaveInfoHeader") + "', " +
                   "'" + GetText(this, GetSaveInfoMessageKey()) + "', " +
                   "'" + GetText(this, "SaveInfoOK") + "', " +
                   "'" + GetText(this, "SaveInfoCancel") + "', " +
                   "true, " +
                   "null" +
                   ");" +
                   "}";
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            tiProperties.OnClientClick = GetClientClickScript(tiProperties);
            tiMemberships.OnClientClick = GetClientClickScript(tiMemberships);
            hlNewMembership.NavigateUrl = "Admin/EditMembership.aspx?userid=" + EditedUserID;
            // Re-fetch the properties tab to keep them updated if the user chose not to save changes
            _presenter.RefreshProperties();
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);
            ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(),
                                                            "updatePanels",
                                                            "updatePanels('" + tabStrip.SelectedValue + "');", true);
            hlNewMembership.Visible = tabStrip.SelectedValue == "memberships";
            lbSave.Visible = tabStrip.SelectedValue == "properties";
            upnlButtons.Update();
        }

        protected void tabStrip_Click(string value)
        {
            if (CurrentTab == "properties" && hidSave.Value == "ok")
                _presenter.Save();
            if (_presenter.IsValid)
            {
                ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init();", true);
            }
            upnlProperties.Update();
            upnlMemberships.Update();
            upnlTabs.Update();
        }

        protected void rpMemberships_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
            {
                return;
            }
            var membership = (Domain.Membership)e.Item.DataItem;
            var litId = (Literal)e.Item.FindControl("litId");
            var litStartDate = (Literal)e.Item.FindControl("litStartDate");
            var litEndDate = (Literal)e.Item.FindControl("litEndDate");
            var litUserGroup = (Literal)e.Item.FindControl("litUserGroup");
            var litSystemId = (Literal)e.Item.FindControl("litSystemId");
            litId.Text = "<span id=\"M" + membership.ID + "\">";
            litUserGroup.Text = membership.UserGroup.Name;
            litStartDate.Text = membership.StartDate.HasValue
                                    ? membership.StartDate.Value.ToShortDateString()
                                    : string.Empty;
            litEndDate.Text = membership.EndDate.HasValue
                                    ? membership.EndDate.Value.ToShortDateString()
                                    : string.Empty;
            litSystemId.Text = membership.ID.ToString();
        }

        protected void lbSave_Click(object sender, EventArgs e)
        {
            _presenter.Save();
            if (_presenter.IsValid)
                Response.Redirect("Users.aspx");
        }

        protected void lbDeleteMembership_Click(object sender, EventArgs e)
        {
            _presenter.DeleteMembership(int.Parse(hidDeleteMembershipID.Value.Substring(1)));
            upnlMemberships.Update();
            ClientScriptProxy.Current.RegisterStartupScript(pnlActions, GetType(), "initMemberships", "initMemberships();", true);
        }
    }
}